package goodenglish.domain.service.impl;

import goodenglish.domain.model.profword.ProfWordLib;
import goodenglish.domain.model.profword.ProfWordLibRepository;
import goodenglish.domain.service.ProfWordsBackService;
import goodenglish.infrastructure.Config;
import goodenglish.infrastructure.DateUtil;
import goodenglish.infrastructure.FileUtil;
import goodenglish.infrastructure.repository.db.ProfWordLibRepositoryDb;
import goodenglish.interfaces.BeanFactory;

import java.io.File;
import java.util.Collections;

/**
 * 
 * @author qiuriyuchen E-mail:panpan_001@126.com
 */
public class ProfWordBackServiceFile implements ProfWordsBackService {

	@Override
	public void backProfWord() {

		ProfWordLib profWordLib = profWordsRepository.getProfWordLib();
		File backFile = new File(Config.BACK_PATH + "/profwords" + DateUtil.getCurrTimeMiniteStr() + ".txt");
		if (null == profWordLib) {
			return;
		}
		StringBuffer savebuffer = new StringBuffer();
		Collections.sort(profWordLib.getWords());
		for (String word : profWordLib.getWords()) {
			savebuffer.append(word);
			savebuffer.append(Config.LINE_SPLITER);
		}
		FileUtil.writeStrToTxtFileReplaceIfExsit(backFile, savebuffer.toString());

		// TODO Auto-generated method stub

	}

	@Override
	public void reBackProfWord(File file) {
		ProfWordLib profWordLib = new ProfWordLib();
		try {

			String str = FileUtil.readTxtFile(file);
			String[] wordsStr = str.split(Config.LINE_SPLITER);
			for (String s : wordsStr) {
				String word = s.trim();
				if (!word.isEmpty()) {
					profWordLib.addProfWord(word);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		profWordsRepository.addOrUpdateProfWordLib(profWordLib);
	}

	private ProfWordLibRepository profWordsRepository = BeanFactory.getSingleInstance(ProfWordLibRepositoryDb.class);
}
